<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button id="btn1">存储</button>
    <button id="btn2">取出打印</button>
    <button id="btn3">删除</button>

    <script>
        let btn1Ele = document.getElementById('btn1');
        let btn2Ele = document.getElementById('btn2');
        let btn3Ele = document.getElementById('btn3');

        // 存：
        // 本地存储只能存字符串,若要存储数组和对象，
        // 需要将其序列化为一个字符串才可以存储
        btn1Ele.addEventListener('click', function () {
            localStorage.setItem('username', '小胡');
            localStorage.setItem('age', 18);
            localStorage.setItem('dark', 'light');
            localStorage.setItem('data', '2024-11-4');
            // 存储对象(或数组)
            // JSON.stringify(数组/对象):将对象或字符串序列换为JSON字符串
            let user = { username: 'SCGO', pwd: 123456 }
            localStorage.setItem('user', JSON.stringify(user));
        });

        // 取:
        btn2Ele.addEventListener('click', function () {
            console.log(localStorage.getItem('username'));
            console.log(localStorage.getItem('age'));
            console.log(localStorage.getItem('dark'));
            console.log(localStorage.getItem('data'));
            // 取出对象(或数组)
            // JSON.parse(json字符串): 将json字符串转化为js对象（或数组）
            let data = JSON.parse(localStorage.getItem('user'));
            console.log(data);
        });

        // 删：
        btn3Ele.addEventListener('click', function () {
            localStorage.removeItem('age');     //删除指定的一个
            localStorage.clear();     //删除全部
        });
    </script>
</body>

</html>